package com.qinhailin.portal.dbm.managectrl;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Record;
import com.qinhailin.common.base.BaseController;
import com.qinhailin.common.model.CTID;
import com.qinhailin.common.routes.ControllerBind;
import com.qinhailin.common.util.MD5Util;
import com.qinhailin.common.vo.Feedback;
import com.qinhailin.portal.core.service.DataDictionaryService;
import com.qinhailin.portal.core.service.DataDictionaryValueService;
import com.qinhailin.portal.dbm.model.DTQuery;
import com.qinhailin.portal.dbm.service.CTIDServiceImpl;
import com.qinhailin.portal.dbm.service.DTQueryServiceImpl;


@ControllerBind(path="/portal/dbm/query")
public class QueryController extends BaseController{
	
	@Inject
	DTQueryServiceImpl service;
	@Inject
	CTIDServiceImpl idService;
	@Inject
	DataDictionaryValueService dicService;
	@Inject
	DataDictionaryService dService;
	
	public void index() {
		//this.set("dictionary", dicService.queryForList("select * from dbo.data_dictionary_value where dictionary_code = ?", "Interval"));
		//dService.
		this.render("index.html");
	}
	
	public void list() {
		//Record record = new Record();
		//this.renderJson(this.service.page(getParaToInt("Record record = new Record();pageNumber", 1), getParaToInt("pageSize", 10), record));
		Record record = new Record();
		record.set("xName", getPara("xName"));
		renderJson(service.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10), record));
	}
	
	public void delete() {
		service.deleteByIds(getIds());
		renderJson(Feedback.success());
	}
	

	
	public void add() {
		//this.set("query", new DTQuery().setXInterval(1));
		this.render("add.html");
	}
	
	
	
	public void save() {
		DTQuery query = this.getBean(DTQuery.class);
		query.setXType(1).setXIDIndex(0).setXMD5(MD5Util.MD5(query.getXText()));
		if(!service.save(query)) {
			setException("保存失败");
		}else {
			CTID id = idService.findByName(query.getXTableName());
			if(id == null) {
				id = new CTID().setXName(query.getXTableName()).setXValue(1);
				idService.save(id);
			}
			query.setXIDIndex(id.getSID());
			service.update(query);
		}
		render("add.html");
	}
	
	
	public void update() {
		DTQuery query = this.getBean(DTQuery.class);
		query.setXType(1);
		if(!service.update(query)) {
			setException("保存失败");
		}
		render("edit.html");
	}
	
	public void edit() {
		DTQuery query = service.findByID(this.getInt());
		setAttr("query", query);
		render("edit.html");
	}

}
